package com.banzhi.shop.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.demo.PayResult;
import com.banzhi.shop.entity.Checkstand.WXPay_Data;
import com.banzhi.shop.model.CallBack.CheckStandCallBack;
import com.banzhi.shop.model.ICheckStandModel;
import com.banzhi.shop.model.Impl.CheckStandImpl;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.Map;

import static com.banzhi.shop.MyApp.APP_ID;

/**
 * 收银台
 */
public class CheckstandActivity extends BaseActivity implements View.OnClickListener, CheckStandCallBack, Handler.Callback {
    private static final int SDK_PAY_FLAG = 0;
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 传过来的订单id
     */
    private String oid;
    /**
     * 传过来的订单价格
     */
    private String goodprice;
    /**
     * 传过来的订单编码
     */
    private String bianma;
    /**
     * 传过来的余额
     */
    private String balance;
    /**
     * 编码
     */
    private TextView tvbianma;
    /**
     * 金额
     */
    private TextView tvjinre;
    /**
     * 余额
     */
    private TextView tvyure;

    /**
     * 余额支付
     */
    private LinearLayout ll_yue;
    /**
     * 微信支付
     */
    private LinearLayout ll_weixing;
    /**
     * 支付宝支付
     */
    private LinearLayout ll_zhifubao;
    private ICheckStandModel model;
    /**
     * 微信支付实体类
     */
    private WXPay_Data pay;
    private Handler handler;
    /**
     * 注册广播接受者
     */
    private Receiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkstand);
        Translucent.setTranslucent(this);
        setinits();
        setLisntenrs();
        Intent intent = getIntent();
        balance = intent.getStringExtra("balance");
        oid = intent.getStringExtra("orderid");
        goodprice = intent.getStringExtra("goodprice");
        bianma = intent.getStringExtra("bianma");
        showViews();
        model = new CheckStandImpl();
        handler = new Handler(this);
        // 注册广播接受者
        receiver = new Receiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.banzhi");
        registerReceiver(receiver, filter);
    }

    private void showViews() {
        tvbianma.setText(bianma);
        tvjinre.setText(NumberUtils.DecimalFormat(goodprice.trim()));
        tvyure.setText(NumberUtils.DecimalFormat(balance));
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        tvbianma = (TextView) findViewById(R.id.tv_bianma);
        tvjinre = (TextView) findViewById(R.id.tv_jine);
        tvyure = (TextView) findViewById(R.id.tv_yure);
        ll_yue = (LinearLayout) findViewById(R.id.ll_pay_yue);
        ll_weixing = (LinearLayout) findViewById(R.id.ll_weixingzhifu);
        ll_zhifubao = (LinearLayout) findViewById(R.id.ll_zhifubao);
    }

    private void setLisntenrs() {
        ivback.setOnClickListener(this);
        ll_yue.setOnClickListener(this);
        ll_weixing.setOnClickListener(this);
        ll_zhifubao.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_pay_yue:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                model.PayYure(oid, goodprice, this);
                break;
            case R.id.ll_weixingzhifu:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                model.PayWX(bianma, goodprice, this);
//                model.PayWX(bianma, "0.01", this);
                break;
            case R.id.ll_zhifubao:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                model.PayZFB(bianma, goodprice, this);
//                model.PayZFB(bianma, "0.01", this);
                break;
        }
    }

    private void WeChatPay(WXPay_Data data) {
        if (null == data) {
            //判断是否为空。丢一个toast，给个提示。比如服务器异常，错误啥的
            ToastUtils.makeToastShort("服务器异常");
            return;
        }
        IWXAPI api = WXAPIFactory.createWXAPI(this, APP_ID);
        if (!api.isWXAppInstalled()) {
            ToastUtils.makeToastShort("没有安装微信");
        }
        if (!api.isWXAppSupportAPI()) {
            ToastUtils.makeToastShort("当前版本不支持支付功能");
        }
        //data  根据服务器返回的json数据创建的实体类对象
        PayReq req = new PayReq();
        req.appId = data.getAppid();
        req.partnerId = data.getPartnerid();
        req.prepayId = data.getPrepayid();
        req.packageValue = "Sign=WXPay";
        req.nonceStr = data.getNoncestr();
        req.timeStamp = data.getTimestamp();
        req.sign = data.getSign();
        api.registerApp(APP_ID);
        //发起请求
        api.sendReq(req);
    }

    /**
     * @param object 余额支付成功
     */
    @Override
    public void onPayYureSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        tvyure.setText(NumberUtils.DecimalFormat(jsonObject.optString("res")));
//        ToastUtils.makeToastShort("支付成功");
        Intent intent = new Intent(this, OrderDetailsActivity.class);
        intent.putExtra("id", oid);
        intent.putExtra("status", "1");
        startActivity(intent);
        finish();

    }

    /**
     * @param object 余额支付失败
     */
    @Override
    public void onPayYureError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 微信支付
     */
    @Override
    public void onPayWXSuccess(Object object) {
        pay = (WXPay_Data) object;
        WeChatPay(pay);
    }

    /**
     * @param object 微信支付
     */
    @Override
    public void onPayWXError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
      //  ToastUtils.makeToastShort(jsonObject.optString("0"));
    }

    /**
     * @param object 支付宝
     */
    @Override
    public void onPayZFBSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        final String orderInfo = jsonObject.optString("data");

        new Thread() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(CheckstandActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = 2;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        }.start();
    }

    /**
     * @param object 支付宝
     */
    @Override
    public void onPayZFBError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
    @Override
    public boolean handleMessage(final Message msg) {

        ToastUtils.makeToastShort("获取订单中...");
        switch (msg.what) {
            case 2:
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String resultInfo = payResult.getResult();
                String resultStatus = payResult.getResultStatus();
                if (TextUtils.equals(resultStatus, "9000")) {
                    ToastUtils.makeToastShort("支付成功");
                    Intent intent = new Intent(this, OrderDetailsActivity.class);
                    intent.putExtra("id", oid);
                    intent.putExtra("status", "1");
                    startActivity(intent);
                    finish();
                } else {
                    if (TextUtils.equals(resultStatus, "8000")) {
                        ToastUtils.makeToastShort("支付结果确认中");
                    } else {
                        ToastUtils.makeToastShort("支付失败");
                    }
                }
                break;

        }
        return false;
    }

    public class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("com.banzhi".equals(action)) {
                ToastUtils.makeToastShort("支付成功");
                Intent wxintent = new Intent(CheckstandActivity.this, OrderDetailsActivity.class);
                wxintent.putExtra("id", oid);
                wxintent.putExtra("status", "1");
                startActivity(wxintent);
                finish();
            }
        }
    }
    @Override
    public void onDestroy() {
        // 注销广播接受者
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
